<template>
  <div>
    <el-upload
      :action="uploadAction"
      :headers="uploadHeaders"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :file-list="fileList"
      :before-upload="beforeFileUpload"
    >
      <el-button type="primary">选择文件</el-button>
    </el-upload>
  </div>
</template>

<script setup>
import $cookie from 'vue-cookies'
import { ElMessage } from 'element-plus'

const uploadHeaders = { Authorization: $cookie.get('Authorization') }
const uploadAction = http.adornUrl('/admin/file/upload/element')
const props = defineProps({
  modelValue: {
    default: '',
    type: String
  }
})
const emit = defineEmits(['update:modelValue'])

const fileList = computed(() => {
  const res = []
  if (props.modelValue) {
    const fileArray = props.modelValue?.split(',')
    for (let i = 0; i < fileArray.length; i++) {
      res.push({ name: fileArray[i], response: fileArray[i] })
    }
  }
  emit('update:modelValue', props.modelValue)
  return res
})

/**
 * 文件上传成功处理
 */
// eslint-disable-next-line no-unused-vars
const handleUploadSuccess = (response, file, fileList) => {
  const files = fileList.map(file => {
    if (typeof file.response === 'string') {
      return file.response
    }
    return file.response.data
  }).join(',')
  emit('update:modelValue', files)
}

/**
 * 限制文件上传大小
 */
const beforeFileUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
  }
  return isLt10M
}

// eslint-disable-next-line no-unused-vars
const handleRemove = (file, fileList) => {
  const files = fileList.map(file => {
    if (typeof file.response === 'string') {
      return file.response
    }
    return file.response.data
  }).join(',')
  emit('update:modelValue', files)
}

</script>